<?php

/**
* AdminAddCodeFormModule.class.php
*
* Concrete page module responsable for adding/editing guide
*
* @author     Blazej Zieba <b@zieba.info>
* @copyright  2007 konekto.com
* @version    CVS: $Id:$
*/

require_once("framework/PageModule.class.php");
require_once("HTML/QuickForm.php");
require_once("HTML/QuickForm/Renderer/Default.php");
require_once("HTML/Template/IT.php");
require_once("ValidationRule.php");
require_once("framework/Yt.class.php");
require_once("framework/Wurfl.class.php");

function onlyOneSet($data)
{

    if(  isSet($data[0]) && $data[1] != '' )
    {
        return false;
    }
    return true;
}  
  
function ytProcessed($id)
{

    $ch = curl_init();

    curl_setopt($ch, CURLOPT_URL, "http://www.youtube.com/watch?hl=pl&v=".$id);
    curl_setopt($ch, CURLOPT_HEADER,0);
    curl_setopt($ch, CURLOPT_USERAGENT, isset($_SERVER["HTTP_USER_AGENT"]) ? $_SERVER["HTTP_USER_AGENT"] : null );
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_HTTPPROXYTUNNEL, 0); 
    $options = &PEAR::getStaticProperty('CONFIG_INI','GLOBAL'); 
    curl_setopt($ch, CURLOPT_PROXY,  isset($options['proxy']) ? $options['proxy'] : null ); 
    $data = curl_exec($ch);
    curl_close($ch);
    if ( strpos($data,"Ten film wideo nie został jeszcze przetworzony.") || 
         strpos($data,"Film wideo jest nadal przetwarzany.") || 
         strpos($data,"Żądany film wideo jest niedostępny.") )
    {

        return true;
    }
    
    return false;
}

function ytPublic($id)
{

    $yt = Yt::getClient();
    try
    {    

        $videoEntry = $yt->getVideoEntry($id);
    }
    catch(Zend_Gdata_App_HttpException $e)
    {
        return false;
    }

    return true;
}

function ytPrivate($id)
{

    $yt = Yt::getClient();
    
    try
    {
        $videoEntry = $yt->getVideoEntry($id,null,true);
    }
    catch(Zend_Gdata_App_HttpException $e)
    {
        return false;
    }

    return true;


}

function ytHref($data)
{
    if( ytPublic($data) || ytProcessed($data) || ytPrivate($data) )
    {
        return true;
    }

    return false;
}


// {{{ SlideShowListModule

class AdminAddCodeFormModule extends PageModule 
{
    // {{{ Class operations 
    private $dbh = null;

    // {{{ SlideShowListModule
    /**
    * C'tor
    */
    
    function AdminAddCodeFormModule()
    {
        trigger_error("ENTER AdminAddCodeFormModule::AdminAddCodeFormModule()", E_USER_NOTICE);

        $options = &PEAR::getStaticProperty('CONFIG_INI','DSN');    
        $this->dbh = new PDO($options['dsn_string']);
        $this->dbh->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );    
    }
    // }}}
    // {{{ getContent

    /**
    * Function returns page content
    *
    */

    function getContent()
    {
    
        if (isset($_GET['id']))
        {
            $defaultValues = AdminAddCodeFormModule::getDefaultValue($_GET['id']);
        }

        trigger_error("ENTER AdminAddCodeFormModule::getContent()", E_USER_NOTICE);

        $options = &PEAR::getStaticProperty('CONFIG_INI','GLOBAL');

        $form = new HTML_QuickForm("AddGuideForm", 'post', rtrim($options['service_url'],'/').'/index.php?cmd=AdminAddCode');

        $form->setMaxFileSize($options['max_file_size']);

        $form->addElement('hidden','id', isset($_GET['id']) ? $_GET['id'] : null);       

        $form->addElement('text', 'name', _('Nazwa kodu:'), array('size' => 50, 'maxlength' => 255));
        $form->addElement('textarea', 'desc', _('Opis kodu:'), array('rows' => 3, 'cols' => 50));

        if (isset($defaultValues['pic_file']) ? $defaultValues['pic_file'] : null )
        {
            $global = &PEAR::getStaticProperty('CONFIG_INI','GLOBAL');
            $options = &PEAR::getStaticProperty('CONFIG_INI','UPLOAD');
            $form->addElement('static', null,_('Aktualne zdjęcie:'), '<img alt="'.$defaultValues['pic_file'].'" src="'.rtrim($global['service_url'],'/').'/send_image.php?id='.$defaultValues['pic_file'].'">');
            $form->addElement('checkbox','delete_pic_file', _('Usuń zdjęcie:'));
        }  

        $form->addElement('file', 'pic_file', _('Zdjęcie:'), array()); 

        if ( isset($defaultValues['video_file']) )
        {
            $options = &PEAR::getStaticProperty('CONFIG_INI','UPLOAD');
            $yt = Yt::getClient();

            try 
            {
                $videoEntry = $yt->getVideoEntry($defaultValues['video_file']);
 
                if (Wurfl::deviceFactory()->getCapability("model_name") == 'iPhone' || 
                    Wurfl::deviceFactory()->getCapability("is_wireless_device") != 'true')
                {
                    foreach ($videoEntry->mediaGroup->content as $content) {
                        if ( $content->format === '5') {
                            $height = Wurfl::deviceFactory()->getCapability("max_image_height");
                            $height = $height > 640 ? 640 : $height;
                            $width = Wurfl::deviceFactory()->getCapability("max_image_width");    
                            $width = $width > 640 ? 640 : $width;

                            $form->addElement('static', null, _('Aktulane video:'), '<object width="'.$width.'" height="'.$height.'" classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" ><param name="movie" value="'.$content->url.'"></param><embed src="'.$content->url.'" type="'.$content->format.'" width="'.$width.'" height="'.$height.'" ></embed></object>');

                        }
                    }
                }
                elseif (Wurfl::deviceFactory()->getCapability("playback_vcodec_mpeg4_sp") >=0)
                {
                    foreach ($videoEntry->mediaGroup->content as $content) {
                        if ( $content->format === '6') {
                            $form->addElement('static', null, _('Aktulane video:'), '<a href="'.$content->url.'">'._('Pobierz video').'</a>');
                        }
                    }
                }
                elseif( Wurfl::deviceFactory()->getCapability("playback_vcodec_h263_0") >= 0 || 
                        Wurfl::deviceFactory()->getCapability("playback_vcodec_h263_3") >= 0 )
                {
                    foreach ($videoEntry->mediaGroup->content as $content) {
                        if ( $content->format === '1') {
                            $form->addElement('static', null, _('Aktulane video:'), '<a href="'.$content->url.'">'._('Pobierz video').'</a>');
                        }
                    }

                }
                else
                {
                    $form->addElement('static', null, _('Wideo niedostępne na twoim telefonie.'));
                }
            } 
            catch ( Zend_Exception $e )
            {
                $form->addElement('static', null, _('Wideo w trakcie przetwarzania'));
            } 
  

            $form->addElement('checkbox','delete_video_file', _('Usuń video:'));
        }
        $form->addElement('file', 'video_file', _('Wideo:'), array());
        $form->addElement('text', 'yt_id', _('YouTube id:'), array('size' => 11, 'maxlength' => 255));
        $yt_id = $form->getElement('yt_id');
        $yt_id -> setValue($defaultValues['video_file']);

        $form->addElement('text', 'geocode', _('Lokalizacja:'), array('size' => 50, 'maxlength' => 255));
        $form->addElement('advcheckbox','publish', _('Opublikowany:'));

        $form->addElement('submit', 'Submit',_('Zapisz'));

        $form->applyFilter('yt_id', 'trim');
        $form->addRule('name', _('Podaj nazwę'), 'required');
        $form->addRule('id', _('Nieprawidłowa wartość id'), 'NumericOrNull');
        $form->addRule('pic_file',_('Niepoprawny format pliku'),'mymimetype','image/');
        $form->addRule('video_file',_('Niepoprawny format pliku'),'mymimetype','video/');

        $form->registerRule('onlyoneset', 'callback', 'onlyOneSet');
        $form->addRule(array('video_file','yt_id'),_('Podaj plik lub id'),'onlyoneset');

        $form->registerRule('ythref', 'callback', 'ytHref');
        $form->addRule('yt_id',_('Nieprawidłowy id'),'ythref');

        $form->setDefaults(isset($defaultValues) ? $defaultValues : null );
 
        $options = &PEAR::getStaticProperty('CONFIG_INI','TEMPLATES');     
        $statusTpl = new HTML_Template_IT($options["templates_dir"]);
        $statusTpl->loadTemplatefile("status.tpl.xhtml",FALSE,FALSE);
        if ($form->validate()) 
        {
            $data = $form->getSubmitValues(true);
            if ( $form->getSubmitValue( 'id' ) )
            {
                $this->updateGuide($data);
                $statusTpl->setVariable("STATUS",_("Kod zaktualizowany."));
            }
            else
            {

                $this->addGuide($data);
                $statusTpl->setVariable("STATUS",_("Kod dodany."));
            }          
         
            return $statusTpl->get();

        }
        else
        {
            $renderer =& new HTML_QuickForm_Renderer_Default($options);
            $renderer -> setFormTemplate(file_get_contents($options["templates_dir"]."form.tpl.xhtml"));
            $renderer -> setElementTemplate(file_get_contents($options["templates_dir"]."formElement.tpl.xhtml"));
            $renderer -> setRequiredNoteTemplate(file_get_contents($options["templates_dir"]."formRequiredNote.tpl.xhtml"));
            $form -> setRequiredNote(_("* pole obowiązkowe")); 
            $form->accept($renderer);

            if (isset($_GET['id']))
            {
                $statusTpl->setVariable("STATUS",_("Edycja kodu"));
            }  
            else
            {
                $statusTpl->setVariable("STATUS",_("Dodaj kod"));
            } 
        
        
	        return $statusTpl->get().$renderer->toHtml().$statusTpl->get();
        }
    }
    
    // }}}

    // {{{
    /**
    * Process data from form 
    */
    
    public function addGuide($data)
    {

        trigger_error("ENTER AdminAddCodeFormModule::addData()", E_USER_NOTICE);

        if ( ! $this->dbh->beginTransaction() )
        {
            trigger_error("AdminAddCodeFormModule::addGuide()  Could not begin transaction !", E_USER_ERROR);
        }

        //Save data
        $element = array("geocode","publish");
        $tableKey = array();
        $tableValue = array();
        foreach( $data as $key => $value ) 
        {
            if ( in_array($key,$element) )
            {
                $tableKey[] = $this->dbh->quote($key);
                $tableValue[] = $this->dbh->quote($value);
            }
        } 
        

        $sth = $this->dbh->prepare("INSERT INTO guide (".implode(",",$tableKey).", owner ) VALUES (".implode(",",$tableValue).",:owner)") ;
        $sth -> bindParam(':owner',  AuthSingleton::instance()->getUsername() ,PDO::PARAM_STR);
        $sth -> execute();   

        $lastId = $this->dbh->lastInsertId();

        //Save desc
       
        $sth = $this->dbh->prepare("INSERT INTO guide_desc (guide_id,locale,desc) VALUES (:guide_id,:locale,:desc)") ;
        $sth -> bindParam(':guide_id',  $lastId ,PDO::PARAM_INT);
        $sth -> bindParam(':locale', LocalizationSingleton::getLocale()  ,PDO::PARAM_STR);
        $sth -> bindParam(':desc', $data['desc'],PDO::PARAM_STR);
        $sth -> execute();  

        //Save name
        $sth = $this->dbh->prepare("INSERT INTO guide_name (guide_id,locale,name) VALUES (:guide_id,:locale,:name)") ;
        $sth -> bindParam(':guide_id',  $lastId ,PDO::PARAM_INT);
        $sth -> bindParam(':locale', LocalizationSingleton::getLocale()  ,PDO::PARAM_STR);
        $sth -> bindParam(':name', $data['name'],PDO::PARAM_STR);
        $sth -> execute();  
        

        //upload video to You Tube
        if ( $data['yt_id'] != '' )//Yt id was provided
        {
            $sth = $this->dbh->prepare("UPDATE guide SET video_file = :video_file WHERE ROWID = :id AND owner = :owner" ) ;
            $sth -> bindParam(':video_file',  $data['yt_id'] ,PDO::PARAM_STR);
            $sth -> bindParam(':owner',  AuthSingleton::instance()->getUsername() ,PDO::PARAM_STR);
            $sth -> bindParam(':id', $lastId, PDO::PARAM_INT);
            $sth -> execute();
        }
        else
        {
            $this->saveVideoToYt($lastId, $data['video_file'], $data['name'], $data['publish']);
        }
        

        // 
        
        
        $options = &PEAR::getStaticProperty('CONFIG_INI','UPLOAD');

        $element = array("pic_file");
        $tableAssigment = array();

        foreach($data as $key => $value)
        {

            if( in_array($key,$element) )
            {
                if ( move_uploaded_file($value["tmp_name"],$options['upload_dir'].$lastId.$value['name']) )
                {
                    $tableAssigment[] = $this->dbh->quote($key)."=".$this->dbh->quote($lastId.$value['name']);
                }
            }
        }
        if ( count ( $tableAssigment ) )
        {

            $sth = $this->dbh->prepare("UPDATE guide SET ".implode(",",$tableAssigment)." WHERE ROWID = :id AND owner = :owner ") ; 
            $sth -> bindParam(':owner',  AuthSingleton::instance()->getUsername() ,PDO::PARAM_STR);
            $sth -> bindParam(':id',  $lastId ,PDO::PARAM_INT);
            $sth -> execute();  
        }

        //Genrate and add code 

        $sth = $this->dbh->prepare("UPDATE guide SET code = :code WHERE ROWID = :id AND owner = :owner ") ; 
        $sth -> bindParam(':code',  $this->generateCode(6) ,PDO::PARAM_STR);
        $sth -> bindParam(':owner',  AuthSingleton::instance()->getUsername() ,PDO::PARAM_STR);
        $sth -> bindParam(':id',  $lastId ,PDO::PARAM_INT);
        $sth -> execute();  

        /*
        //geocode
        if ( $data['geocode'] ) 
        {
            $location = $this->getGeoLocation($data['geocode']);

            if ( $location['status'] == "200" )
            {
                $sth = $this->dbh->prepare("UPDATE guide SET precision = :precision , latitude = :latitude , longitude =  :longitude  WHERE ROWID = :id AND owner=:owner") ; 
                $sth -> bindParam(':precision', $location['precision'] );
                $sth -> bindParam(':latitude', $location['latitude'] );
                $sth -> bindParam(':longitude',$location['longitude']);
                $sth -> bindParam(':id',$lastId,PDO::PARAM_INT);
                $sth -> bindParam(':owner',  AuthSingleton::instance()->getUsername() ,PDO::PARAM_STR);
                $sth -> execute();         
            }
        }
        */
        if ( ! $this->dbh->commit() )
        {
            trigger_error("AdminAddCodeFormModule::addGuide() Could not end transaction!", E_USER_ERROR);
        }

        //Save to database     
        
    }
    // }}}

    // {{{
    /**
    * Process data from form and update 
    */
    
    public function updateGuide($data)
    {
        
        trigger_error("ENTER AdminAddCodeFormModule::updateGuide()", E_USER_NOTICE);

        if ( ! $this->dbh->beginTransaction() )
        {
            trigger_error("AdminAddCodeFormModule::updateGuide()  Could not begin transaction", E_USER_ERROR);
        }

        $options = &PEAR::getStaticProperty('CONFIG_INI','DSN');    
        //Save data
        $element = array("geocode","publish");
        $tableAssigment = array();
        foreach( $data as $key => $value ) 
        {
            if ( in_array($key,$element) )
            {
                $tableAssigment[] = $this->dbh->quote($key)."=".$this->dbh->quote($value);
            }
        } 

        $sth = $this->dbh->prepare("UPDATE guide SET ".implode(",",$tableAssigment)."  WHERE ROWID = :id AND owner = :owner") ;
        $sth -> bindParam(':owner',  AuthSingleton::instance()->getUsername() ,PDO::PARAM_STR);
        $sth -> bindParam(':id',  $data['id'] ,PDO::PARAM_INT);
        $sth -> execute();  

        //Save desc
        $sth = $this->dbh->prepare("DELETE FROM guide_desc WHERE guide_id = :guide_id AND locale = :locale") ;
        $sth -> bindParam(':guide_id',  $data['id'] ,PDO::PARAM_INT);
        $sth -> bindParam(':locale', LocalizationSingleton::getLocale()  ,PDO::PARAM_STR);
        $sth -> execute();  

        $sth = $this->dbh->prepare("INSERT INTO guide_desc (guide_id,locale,desc) VALUES (:guide_id,:locale,:desc)") ;
        $sth -> bindParam(':guide_id',  $data['id'] ,PDO::PARAM_INT);
        $sth -> bindParam(':locale', LocalizationSingleton::getLocale()  ,PDO::PARAM_STR);
        $sth -> bindParam(':desc', $data['desc'],PDO::PARAM_STR);
        $sth -> execute();  

        //Save name
        $sth = $this->dbh->prepare("DELETE FROM guide_name WHERE guide_id = :guide_id AND locale = :locale") ;
        $sth -> bindParam(':guide_id',  $data['id'] ,PDO::PARAM_INT);
        $sth -> bindParam(':locale', LocalizationSingleton::getLocale()  ,PDO::PARAM_STR);
        $sth -> execute();  
        
        $sth = $this->dbh->prepare("INSERT INTO guide_name (guide_id,locale,name) VALUES (:guide_id,:locale,:name)") ;
        $sth -> bindParam(':guide_id',  $data['id'] ,PDO::PARAM_INT);
        $sth -> bindParam(':locale', LocalizationSingleton::getLocale()  ,PDO::PARAM_STR);
        $sth -> bindParam(':name', $data['name'],PDO::PARAM_STR);
        $sth -> execute();  

        $options = &PEAR::getStaticProperty('CONFIG_INI','UPLOAD');

        //Delete uploaded files ?
        if ( isset($data['delete_pic_file']) )
        {
            $sth = $this->dbh->prepare("SELECT pic_file FROM guide WHERE ROWID = :id AND owner = :owner") ; 
            $sth -> bindParam(':owner',  AuthSingleton::instance()->getUsername() ,PDO::PARAM_STR);
            $sth -> bindParam(':id',  $data['id'] ,PDO::PARAM_INT);
            $sth -> execute();  
            $result = $sth->fetch(PDO::FETCH_ASSOC);

            $sth = $this->dbh->prepare("UPDATE guide SET pic_file = null WHERE ROWID = :id AND owner = :owner") ; 
            $sth -> bindParam(':owner',  AuthSingleton::instance()->getUsername() ,PDO::PARAM_STR);
            $sth -> bindParam(':id',  $data['id'] ,PDO::PARAM_INT);
            $sth -> execute();  

            if ( !unlink($options['upload_dir'].$result['pic_file'])  )
            {
                trigger_error("AdminAddCodeFormModule::updateGuide()  Could not remove file ".$options['upload_dir'].$result['pic_file'], E_USER_ERROR);
            }
        }

        if ( $data['yt_id'] != ''  )
        {
            //yt_id provided 
            $sth = $this->dbh->prepare("UPDATE guide SET video_file = :video_file WHERE ROWID = :id AND owner = :owner" ) ;
            $sth -> bindParam(':video_file',  $data['yt_id'] ,PDO::PARAM_STR);
            $sth -> bindParam(':owner',  AuthSingleton::instance()->getUsername() ,PDO::PARAM_STR);
            $sth -> bindParam(':id', $data['id'], PDO::PARAM_INT);
            $sth -> execute();
        }

        if ( isset($data['delete_video_file']) || $data['yt_id'] == '' )
        {
        
            $this->deleteVideoFromYt( $data['id'] );
            
        }

        $this->updateVideoToYt( $data['id'], $data['video_file'], $data['name'], $data['publish']); 

        $this->publishVideoOnYt($data['id'], $data['publish']);

        $element = array("pic_file");
        $tableAssigment = array();

        foreach($data as $key => $value)
        {

            if( in_array($key,$element) )
            {
                if ( move_uploaded_file($value["tmp_name"],$options['upload_dir'].$data['id'].$value['name']) )
                {
                    $tableAssigment[] = $this->dbh->quote($key)."=".$this->dbh->quote($data['id'].$value['name']);
                }
            }
        }

        if ( count ( $tableAssigment ) )
        {
            $sth = $this->dbh->prepare("UPDATE guide SET ".implode(",",$tableAssigment)." WHERE ROWID = :id AND owner = :owner") ; 
            $sth -> bindParam(':owner',  AuthSingleton::instance()->getUsername() ,PDO::PARAM_STR);
            $sth -> bindParam(':id',  $data['id'] ,PDO::PARAM_INT);
            $sth -> execute(); 
        }
        
        /*
        //geocode
        if ( $data['geocode'] ) 
        {
            $location = $this->getGeoLocation($data['geocode']);

            if ( $location['status'] == "200" )
            {
                $sth = $this->dbh->prepare("UPDATE guide SET precision = :precision , latitude = :latitude , longitude =  :longitude  WHERE ROWID = :id AND owner = :owner") ; 
                $sth -> bindParam(':precision', $location['precision'] );
                $sth -> bindParam(':latitude', $location['latitude'] );
                $sth -> bindParam(':longitude',$location['longitude']);
                $sth -> bindParam(':id',$data['id']);
                $sth -> bindParam(':owner',  AuthSingleton::instance()->getUsername() ,PDO::PARAM_STR);
                $sth -> execute();         
            }
        }
        */

        if ( ! $this->dbh->commit() )
        {
            trigger_error("AdminAddCodeFormModule::updateGuide()  Could not end transaction !", E_USER_ERROR);
        }
        //Save to database     
        
    }
    // }}}

    // {{{ getDefaultValues
    /**
    * getDefaultValues
    */
    
    function getDefaultValue($id)
    {

        trigger_error("ENTER AdminAddCodeFormModule::getDefaultValues()", E_USER_NOTICE);

        $options = &PEAR::getStaticProperty('CONFIG_INI','DSN');    
        $this->dbh = new PDO($options['dsn_string']);
        $this->dbh->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
        $sth = $this->dbh->prepare("SELECT *,
            (SELECT name FROM guide_name WHERE guide_name.locale = :locale AND guide_name.guide_id = :id ) AS name , 
            (SELECT desc FROM guide_desc WHERE guide_desc.locale = :locale AND guide_desc.guide_id = :id ) AS desc 
            FROM guide WHERE ROWID = :id AND owner = :owner");
        $sth -> bindParam(':locale',  LocalizationSingleton::getLocale(), PDO::PARAM_STR);
        $sth -> bindParam(':owner',  AuthSingleton::instance()->getUsername() ,PDO::PARAM_STR);
        $sth -> bindParam(':id',  $id ,PDO::PARAM_INT);
        $sth -> execute(); 
        $result = $sth->fetch(PDO::FETCH_ASSOC);
        return $result;
    }
    // }}}


    // {{{ generateCode
    /**
     * Generate random code  unique for whole db
     *
     */
    

      function generateCode($length = "")
      {

            $code = md5(uniqid(rand(), true));

            if ($length != "") 
            {
                return substr($code, 0, $length);
            }

            return $code;
      }


    // }}}

    // {{{ saveVideoToYt

    /**
    * Save video to YouTube
    *
    */
    function saveVideoToYt($lastId, $uploadedVideo, $title, $publish = 1)    
    {
        trigger_error("AdminAddCodeFormModule::saveVideoToYt()", E_USER_NOTICE );
        if( !is_uploaded_file($uploadedVideo['tmp_name']) ) 
        { 
            return; 
        }
        $yt = Yt::getClient();
        Zend_Loader::loadClass('Zend_Gdata_YouTube');
        $global = &PEAR::getStaticProperty('CONFIG_INI','GLOBAL'); 
        // create a new VideoEntry object
        $myVideoEntry = new Zend_Gdata_YouTube_VideoEntry();

        $myVideoEntry->setVideoTitle($title);
        $myVideoEntry->setVideoDescription($title);
        $myVideoEntry->setVideoCategory('People');
        $myVideoEntry->SetVideoTags($global['service_url']);


        if( $publish != 1 )
        {
            $myVideoEntry->setVideoPrivate();
        }


        $tokenHandlerUrl = 'http://gdata.youtube.com/action/GetUploadToken';
        $tokenArray = $yt->getFormUploadToken($myVideoEntry, $tokenHandlerUrl);
        $tokenValue = $tokenArray['token'];
        $postUrl = $tokenArray['url'];

        // place to redirect user after upload
        $nextUrl = $global['service_url'];

        $ch = curl_init();
         
        curl_setopt($ch, CURLOPT_URL, $postUrl .'?nexturl='. $nextUrl);
        curl_setopt($ch, CURLOPT_HEADER,1);
        curl_setopt($ch, CURLOPT_USERAGENT, isset($_SERVER["HTTP_USER_AGENT"]) ? $_SERVER["HTTP_USER_AGENT"] : null );
        curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 0);//do not follow location
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_HTTPPROXYTUNNEL, 0);//no tunnel
        $options = &PEAR::getStaticProperty('CONFIG_INI','GLOBAL'); 
        curl_setopt($ch, CURLOPT_PROXY,  isset($global['proxy']) ? $global['proxy'] : null ); 
        curl_setopt($ch, CURLOPT_POST, true);
        $post = array(
            "file"=>"@".$uploadedVideo['tmp_name'],
            "token"=>$tokenValue,
        );
        curl_setopt($ch, CURLOPT_POSTFIELDS, $post); 

        $data = curl_exec($ch);
        curl_close($ch);
        //wait a while to avoid google too many calls error
        sleep(1);

        if ( strpos($data, '?status=200' ) === false )
        {
            preg_match('/status=(...)/',$data,$matches);
            trigger_error("AdminAddSlideFormModule::saveVideoToYt()  Video upload failed. Code : ".$data, E_USER_ERROR);
        }

        //Finally save data to db
        $sth = $this->dbh->prepare("UPDATE guide SET video_file = :video_file WHERE ROWID = :id AND owner = :owner" ) ;
        preg_match('/\&id=(.*)\r\n/',$data,$matches);
        $sth -> bindParam(':video_file',  $matches[1]);
        $sth -> bindParam(':owner',  AuthSingleton::instance()->getUsername() ,PDO::PARAM_STR);
        $sth -> bindParam(':id', $lastId, PDO::PARAM_INT);
        $sth -> execute();  
    }
    // }}}

    // {{{ updateVideoToYt

    /**
    * Update video to YouTube
    *
    */
    function updateVideoToYt( $id, $uploadedVideo, $title, $publish)
    {
        trigger_error("ENTER AdminAddCodeFormModule::updateVideoToYt() ", E_USER_NOTICE );
        if( !is_uploaded_file($uploadedVideo['tmp_name']) ) 
        { 
            return; 
        }
        
        trigger_error("AdminAddCodeFormModule::updateVideoToYt() Save to db", E_USER_NOTICE );
        $sth = $this->dbh->prepare("SELECT video_file FROM guide WHERE ROWID = :id AND owner = :owner") ; 
        $sth -> bindParam(':id', $id, PDO::PARAM_INT);
        $sth -> bindParam(':owner',  AuthSingleton::instance()->getUsername() ,PDO::PARAM_STR);
        $sth->execute( ); 
        $result = $sth->fetch(PDO::FETCH_ASSOC);
    
        if ( $result['video_file'] != '' )
        {
            trigger_error("AdminAddCodeFormModule::updateVideoToYt() video file exists ! Delete !", E_USER_NOTICE );
            $this->deleteVideoFromYt($id);
        }

        trigger_error("AdminAddCodeFormModule::updateVideoToYt() save new video", E_USER_NOTICE );
        $this->saveVideoToYt( $id, $uploadedVideo, $title, $publish );
    }
 
    // }}}

    // {{{ deleteVideoFromYt

    /**
    * Delete video file from You Tube
    *
    */
    function deleteVideoFromYt( $id )
    {
        trigger_error("AdminAddCodeFormModule::deleteVideoFromYt()", E_USER_NOTICE );
        $sth = $this->dbh->prepare("SELECT video_file FROM guide WHERE  ROWID = :id AND owner = :owner") ; 
        $sth -> bindParam(':id', $id, PDO::PARAM_INT);
        $sth -> bindParam(':owner',  AuthSingleton::instance()->getUsername() ,PDO::PARAM_STR);
        $sth->execute( ); 
        $result = $sth->fetch(PDO::FETCH_ASSOC);

        $sth = $this->dbh->prepare("UPDATE guide SET video_file = null WHERE   ROWID = :id AND owner = :owner") ; 
        $sth -> bindParam(':id', $id, PDO::PARAM_INT);
        $sth -> bindParam(':owner',  AuthSingleton::instance()->getUsername() ,PDO::PARAM_STR);
        $sth->execute( ); 

        if($result['video_file'] == '')
        {
            return;
        }

        $yt = Yt::getClient();
        
        try
        {
            $videoEntry = $yt->getVideoEntry($result['video_file'],null,true);
            $yt->delete($videoEntry);
        }
        catch(Zend_Gdata_App_HttpException $e)
        {
            trigger_error("AdminAddCodeFormModule:: deleteVideoFromYt() Could not remove video id =  ".$result['video_file'], E_USER_WARNING );
        }
        

    }
 
    // }}}

    // {{{ publishVideoOnYt

    /**
    * Publish / unpublish video on YT
    *
    */
    function publishVideoOnYt( $id, $publish )
    {
      
        $sth = $this->dbh->prepare("SELECT video_file,publish FROM guide WHERE  ROWID = :id AND owner = :owner") ; 
        $sth -> bindParam(':id', $id, PDO::PARAM_INT);
        $sth -> bindParam(':owner',  AuthSingleton::instance()->getUsername() ,PDO::PARAM_STR);
        $sth->execute( ); 
        $result = $sth->fetch(PDO::FETCH_ASSOC);
        
        if( $result['video_file'] != '' )
        {   
            
            $yt = Yt::getClient();
            
            try
            {
                $videoEntry = $yt->getVideoEntry($result['video_file'],null,true);
                $putUrl = $videoEntry->getEditLink()->getHref();

                if($publish == 1 )
                {
     
                    $videoEntry->setVideoPublic();
                }
                else
                {
                    $videoEntry->setVideoPrivate();
                }
                
                $yt->updateEntry($videoEntry, $putUrl);


            }
            catch(Zend_Gdata_App_HttpException $e)
            {
                trigger_error("AdminAddSlideFormModule::publishVideoOnYt() Could not modify video id =  ".$result['video_file'], E_USER_WARNING );
            }
                    
            
 
        }



    }
 
    // }}}

    // {{{ getGeoLocation

    /**
    * Function get location from geocode 
    *
    */
    private function getGeoLocation($geocode)
    {
        trigger_error("AdminAddSlideFormModule::getGeoLocation() $geocode",  E_USER_NOTICE);
        $options = &PEAR::getStaticProperty('CONFIG_INI','GOOGLEMAPKEY'); 
        //Set up our variables
        $status = "";
        $longitude = "";
        $latitude = "";
        $precision = "";
         
        //Three parts to the querystring: q is address, output is the format (
        $key = $options['key_geocoding'];
        $address = urlencode($geocode);
        $url = "http://maps.google.com/maps/geo?q=".$address."&output=csv&key=".$key;
         
        $ch = curl_init();
         
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_HEADER,0);
        curl_setopt($ch, CURLOPT_USERAGENT, isset($_SERVER["HTTP_USER_AGENT"]) ? $_SERVER["HTTP_USER_AGENT"] : null );
        curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_HTTPPROXYTUNNEL, 0); 
        $options = &PEAR::getStaticProperty('CONFIG_INI','GLOBAL'); 
        curl_setopt($ch, CURLOPT_PROXY,  isset($options['proxy']) ? $options['proxy'] : null ); 


        $data = curl_exec($ch);
        curl_close($ch);
        //wait a while to avoid google too many calls error
        sleep(1);
         
        //Check our Response code to ensure success
        $status = substr($data,0,3);
        if ($status == "200")
        {
            $data = explode(",",$data);
         
            $precision = $data[1];
            $latitude = $data[2];
            $longitude = $data[3];
             
        } else {
            trigger_error("AdminAddSlideFormModule::getGeoLocation() Error in geocoding! Http error ".$status, E_USER_WARNING );
        }
        //A few people have mentioned that after some number of requests 
        //(between 100-300) in quick succession google will kill your access for the day,
        // so you may want to insert a
        sleep(1);
        return(array('status' => $status, 'precision' => $precision, 'latitude' => $latitude, 'longitude' => $longitude));
    }
    // }}}

}

// }}} 

?>
